import $ from 'jquery'

export default ({
  state: {
    id: '',
    username: '',
    photo: '',
    followerCount: 0,
    token: '',
    is_login: false,
  },
  getters: {
  },
  mutations: {
    updateUser(state, user) {
        state.id = user.id;
        state.username = user.username;
        state.photo = user.photo;
        state.followerCount = user.followerCount;
        state.is_login = user.is_login;
    },
    updateToken(state, token) {
        state.token = token;
    },
    logout(state){
      state.id = '';
      state.username = '';
      state.photo = '';
      state.followerCount = 0;
      state.token = '';
      state.is_login = false;
    },

  },
  actions: {
    login(context, data) {//根据用户名和密码，获取token
        $.ajax({
            url: 'http://127.0.0.1:3005/user/account/token/',
            type: 'post',
            data: {
                username: data.username,
                password: data.password,
            },
            success(resp) {
              if(resp.error_message === 'success') {
                // console.log(resp.token);
                context.commit('updateToken', resp.token);
                localStorage.setItem('myspace_token', resp.token);
                data.success();//成功获取到token后调用success函数
              }
            },
            error() {
              data.error();
            }
        });
    },

    getinfo(context, data) {//根据token获取用户信息
      $.ajax({
        url: 'http://127.0.0.1:3005/user/account/info/',
        type: 'get',
        headers: {//需要对token进行验证
          Authorization: 'Bearer ' + context.state.token,
        },
        success(resp) {
          if(resp.error_message === 'success') {
            console.log(resp);
            context.commit('updateUser', {
              ...resp,
              is_login: true,
            });
            data.success();
          }
        }
      });
    },

    logout(context) {
      localStorage.removeItem('myspace_token');
      context.commit('logout');
    }
  },
  modules: {
  }
})